<template>
  <!-- 登录模态框 -->
  <div class="model">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowModal(false)"></div>
    <!--  -->
    <div class="loginBox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowModal(false)"></div>
      <!-- 导航 -->
      <section class="nav">
        <a
          href="javaScript:;"
          :class="{ active: isShow }"
          @click="isShow = true"
          >手机号码登录</a
        >
        |
        <a
          href="javaScript:;"
          :class="{ active: !isShow }"
          @click="showQr"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容 -->
      <div class="content">
        <!-- 手机号码  内容· -->
        <div class="phoneLogin" v-show="isShow">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
              ref="phone"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              :accuracy="10"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />
            <button class="btn btncode" @click="getcode" v-show="!isShowCount">
              获取短信验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录步骤二：定义一个id  内容 -->
        <div id="weixin" class="qrLogin" v-show="!isShow"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations,mapActions} from "vuex";
import { validateTelephoneNumber } from "@/utils";
import { SendsMsAPI, PhoneLoginAPI,BindPhoneAPI} from "@/request/api.js";
export default {
  data() {
    return {
      isShow: true,
      msg: "向右滑动",
      phoneNumber: "", //手机号
      count: 60, //秒数
      isShowCount: false, //是否显示倒计时
      code: "", //验证码
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowModal: "showModal/changeIsShowModal",
      changeIsLogined:"loginModal/changeIsLogined",
    }),
    ...mapActions({
      asyncIsShowToast:"showToast/asyncIsShowToast",
      asyncUserInfo:"userInfo/asyncUserInfo"
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 倒计时（函数分装）解决代码复用问题
    countdown() {
      this.count--;
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          clearInterval(timer);
          this.count = 60;
          this.isShowCount = false; //不显示文字
        }
      }, 1000);
    },
    //封装手机校验 和 验证码
    toVerify() {
      //validateTelephoneNumber import 引入 utils工具包
      if (!validateTelephoneNumber(this.phoneNumber)) {
        // alert("手机格式不正确");
         this.asyncIsShowToast({
                show:true,
                msg:"请先输入正确的手机号码",
                type:"danger"
            });
        //操作dom文本框聚焦
        this.$refs.phone.focus();
        return false;
      }
      // if(this.msg=="再试一次" || this.msg =="向右滑动"){
      //   this.asyncIsShowToast({
      //           show:true,
      //           msg:"请滑动验证",
      //           type:"danger"
      //       });
      //   return false;
      // }
      return true;
    },
    async getcode() {
      //1.校验手机号码  提示  如果手机号码不正确直接return
      //2.滑块拼图验证  提示
      if (!this.toVerify()) {
        return;
      }
      //请求发送验证码
      let res = await SendsMsAPI({
        // 请求体  手机号
        phone: this.phoneNumber,
      });
      // console.log("发送验证码", res);
      // 如果code转态为0则成功
      // 接收拦截器返回的data 取反 返回是false直接结束
      if (!res) return;
      if (res.code == 0) {
        alert("发送验证码成功");
        //倒计时
        this.countdown();
        this.isShowCount = true;
      }
    },
    //3.点击验证 发起请求获取验证码 倒计时 文字与秒的切换
    async submitFn() {
      if (!this.toVerify()) {
        return;
      }
      // 判断用户输入的验证码是否为空 空则直接return并提示
      if (this.code.trim() == "") {
        alert("请输入验证码");
        return;
      }
      //登录
      let uuid = localStorage.getItem("uuid")
      let res = null
      // 如果有uuid
      if(uuid){
        res = await BindPhoneAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid
        })
      }
     res = await PhoneLoginAPI({
        verifyCode: this.code,
        phone: this.phoneNumber,
      });
      if (!res) {
        return;
      }
      // 登录成功`
      this.asyncIsShowToast({
                show:true,
                msg:"登录成功",
                type:"success"
            });
      //存储token值到本地储存中
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 隐藏登录模态窗口
      this.changeIsShowModal(false);
      // 登录状态值切换
      this.changeIsLogined(true);
      // 微信绑定 删除uuid
      localStorage.removeItem("uuid")
      //微信绑定 删除地址栏中的code
      this.$router.push(this.$route.path)
      // 更新
      this.asyncUserInfo()
    },
    showQr(){
    this.isShow = false;
          //获取二维码 并展示
          // 申请微信登录二维码
          let _this = this;
          new WxLogin({
            id: "weixin",
            appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
            scope: "snsapi_login",
            // 扫码成功后重定向的接口
            redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
            // state填写编码后的url
            state: encodeURIComponent(
              window.btoa("http://127.0.0.1:8080" + _this.$route.path)
            ),
            // 调用样式文件
            href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0K",
          });
  }
  },
};
</script>

<style lang="less" scoped>
.model {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }
  .loginBox {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    height: 423px;
    width: 555px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      height: 22px;
      width: 22px;
      background: url("../assets/img/close.png");
      cursor: pointer;
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      color: #999;
      a {
        text-decoration: none;
        color: #999;
        padding: 0 10px;
        &.active {
          color: #000;
        }
      }
    }
    .content {
      width: 350px;
      margin: 20px auto 0;
      height: 300px;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          flex: 1;
          height: 45px;
          padding-left: 10px;
          outline: none;
        }
        .btn {
          background-color: #0a328e;
          color: #fff;
          border: none;
          line-height: 45px;
          cursor: pointer;
          width: 110px;
        }
        .btncode {
          margin-left: 10px;
        }
        .btnlogin {
          width: 100%;
        }
      }
    }
  }
}
//滑动插件的css
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
#weixin{
  text-align: center
}
</style>